##########################################
## Copyright 2012-2013 Ceruti Francesco & contributors
##
## This file is part of LiSP (Linux Show Player).
##########################################

import urllib.request as url

try:
    from lxml import etree
except ImportError:
    import xml.etree.ElementTree as etree


class XmlWriter:

    tag = {
           'medialist': 0,
           'program': 1,
           'plugins': 2
           }

    def __init__(self, file):
        self.file = file
        self.root = etree.Element('{LiSP}list')
        self.root.append(etree.Element('medialist'))
        self.root.append(etree.Element('program'))
        self.root.append(etree.Element('plugins'))

    def appendMedia(self, conf, uuid):
        media = etree.Element('media')
        for opt in conf:
            media.append(etree.Element('option', attrib={'name': opt, 'value': url.pathname2url(str(self.format(conf[opt])))}))
        media.append(etree.Element('option', attrib={'name': 'uuid', 'value': url.pathname2url(uuid)}))
        self.root[self.tag['medialist']].append(media)

    def appendPluginSettings(self, plugin, conf):
        plugin = etree.Element('plugin', attrib={'name': plugin})
        for opt in conf:
            plugin.append(etree.Element('option', attrib={'name': opt, 'value': url.pathname2url(str(self.format(conf[opt])))}))
        self.root[self.tag['plugins']].append(plugin)

    def appendProgramSettings(self, conf):
        for opt in conf:
            self.root[self.tag['program']].append(etree.Element('option', attrib={'name': opt, 'value': url.pathname2url(str(self.format(conf[opt])))}))

    def writeFile(self):
        with open(self.file, mode='w', encoding='utf-8') as a_file:
            a_file.write(str(etree.tostring(self.root, pretty_print=True)).replace('ns0:', '').replace(':ns0', '').replace('\\\'', '\'').replace('b\'<', '<').replace('n\'', 'n').replace('\\n', '\n'))

    def format(self, obj):
        if(isinstance(obj, str)):
            obj = '\"' + obj + '\"'
        return obj
